import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import to from "await-to-js";
import { getUserInfo as getUserInfoApi } from "@/api/login";
import cache from "@/plugins/cache";
import { message } from "antd";
import { decrypt, encrypt } from "@/utils/aes";

// 每次进入页面先查看是否有用户信息
let localUserInfo = cache.local.getJSON("userInfo")
  ? cache.local.getJSON("userInfo")
  : null;
let decryptLocalUserInfo;
// 判断用户信息是否失效，如果失效则提示重新登录
if (localUserInfo) {
  if (localUserInfo.saveTime < new Date().getTime()) {
    // 如果已经过期则清除所有缓存
    localStorage.clear();
    localUserInfo = {};
    message.warning("登录状态已失效请重新登录");
  } else {
    // 解密用户信息
    decryptLocalUserInfo = JSON.parse(decrypt(localUserInfo));
    // console.log("解密", JSON.parse(decryptLocalUserInfo));
  }
}

/**
 * 自定义异步获取用户数据方法
 * @params 'getUserInfo'为名字，必须通过返回值然后在extraReducers中拿到
 */
export const getUserInfo = createAsyncThunk(
  "getUserInfo",
  async (token: string) => {
    // console.log(token);
    // 保存token
    const encryptToken = encrypt(token);
    cache.local.set("token", encryptToken);
    const [err, res] = await to(getUserInfoApi());
    if (!err) {
      return res;
    }
  }
);

export const useUserSlice = createSlice({
  name: "user",
  initialState: {
    userInfo: decryptLocalUserInfo,
  },
  reducers: {
    // 保存userInfo
    saveUserInfo(state, action) {
      //   state.userInfo = payload.value;
      console.log(action);
    },
    clearUserInfo(state, action) {
      console.log(action);
    },
  },
  //   这里可以触发其他slice中的方法
  extraReducers: {
    // 异步getUserInfo方法成功的回调
    [getUserInfo.fulfilled](state: any, { payload }) {
      //   console.log(payload);
      state.userInfo = payload.data.user;
      // 手动设置7天过期时间
      payload.data.user.saveTime =
        new Date().getTime() + 1000 * 60 * 60 * 24 * 7;
      // 本地保存用户信息
      const encryptUserInfo = encrypt(payload.data.user);
      cache.local.setJSON("userInfo", encryptUserInfo);
    },
  },
});

export const { saveUserInfo, clearUserInfo } = useUserSlice.actions;

// 这个就是外面引入的userReducer
export default useUserSlice.reducer;
